package animation
{
	import flash.display.Bitmap;
	import flash.utils.getTimer;

	public class Animation extends Bitmap implements IAnimation
	{
		
		public static var ANIMATION_END:int = -1;
		
		private var data:AnimationData;	//播放资源
				
		private var beginTime:Number;
			
		private var playTime:int;		//播放时间
		
		private var totalCurrentNum:int; 	//播放次数
		
		private var animationFps:int;			//帧频率
		
		private var callBack:Function;	//回调函数
		
		private var current:int			//当前已播发次数
		
		private var currentFrame:int;	//当前播放的帧
		
		
		public function Animation()
		{
			data = null;
			
			beginTime 	= ANIMATION_END;
			totalCurrent	= 0;
			playTime 	= 0;
			fps			= 1;
			callBack 	= null;
			
			current = 0;
			currentFrame = 0;
		}
		/**
		 * 设置动画 
		 * @param data 			动画资源
		 * @param time  	播放时间	 (0 没有时间限止，无限播放)
		 * @param num			播放次数 （0，没有次数限止）
		 * @param fps				帧频  警告（该参数不能写0，只能大于零）
		 * @param callBack		回调函数
		 * 
		 */		
		public function setAnimation(data:AnimationData, time:int, num:int = 0, fps:int = 10, callBack:Function = null):void
		{
			stop();
			
			data = data;
			this.playTime = time;
			this.totalCurrent = num;
			this.fps = fps;
			callBack = callBack;
		}
		
		private function clear():void
		{
			current = 0;
			currentFrame = 0;
		}
		
		public function paly():void
		{
			beginTime = getTimer();
			
			clear();
		}
		
		public function stop():void
		{
			beginTime = ANIMATION_END;
		}
		
		public function updata():void
		{
			if(beginTime == ANIMATION_END || !data)
				return;
			
			var num:Number = getTimer() - beginTime;
			
			if((playTime != 0 && num >= playTime) || (totalCurrent !=0 && current >= totalCurrent))
			{
				stop();
				palyOver();
			}
			
			currentFrame = num / fps % data.frameNum;
			
			if(currentFrame == data.frameNum -1)
			{
				current++;
			}

			this.bitmapData = data.bitmapDataList[currentFrame];
		}
		
		private function palyOver():void
		{
			callBack && callBack();
		}
		
		public function release():void
		{
			
		}

		public function get fps():int
		{
			return animationFps;
		}

		public function set fps(value:int):void
		{
			if(value <= 0)
				value = 1;
			
			animationFps = value;
		}

		public function get playTimer():int
		{
			return playTime;
		}

		public function set playTimer(value:int):void
		{
			playTime = value;
		}

		public function get totalCurrent():int
		{
			return totalCurrentNum;
		}

		public function set totalCurrent(value:int):void
		{
			totalCurrentNum = value;
		}
		
		
	}
}